//
//  NSDate-Extension.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/12.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit

extension NSDate{
    class func createDateString(createAtStr : String) ->String {
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        // 将字符串时间,转成NSDate类型
        guard let createDate = fmt.date(from: createAtStr) else{
            return ""
        }
        
        let nowDate = Date()
        
        let interval = Int(nowDate.timeIntervalSince(createDate))
        
        // 5.1.显示刚刚
        if interval < 60{
            return "刚刚"
        }
        // 5.2.59分钟前
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        // 5.3.11小时前
        if interval < 60 * 60 * 24 {
            return "\(interval / (60 * 60))小时前"
        }
        
        
        let calendar = Calendar.current
        
        // 5.5.处理昨天数据: 昨天 12:23
        if calendar.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        //5.6.处理一年之内:
        let cmps = calendar.dateComponents([.year], from: createDate, to: nowDate)
        if cmps.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        // 5.7.超过一年:
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: createDate)
        return timeStr
     
    }
}

